package com.learn.io.bio.bothway;

import com.learn.constant.CommonConstant;
import com.learn.constant.MathConstant;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * 客户端
 */
public class SocketClient {

    static String message = "你好  我给你发一条消息";

    public static void main(String args[]) throws Exception {
        // 要连接的服务端IP地址和端口
        String host = CommonConstant.SOCKET_SERVER_HOST;
        int port = CommonConstant.SOCKET_SERVER_PORT;

        // 与服务端建立连接
        Socket socket = new Socket(host, port);
        // 建立连接后获得输出流
        OutputStream outputStream = socket.getOutputStream();
        socket.getOutputStream().write(message.getBytes(CommonConstant.DEFAULT_CHARSET_NAME));

        //通过shutdownOutput高速服务器已经发送完数据，后续只能接受数据
        socket.shutdownOutput();

        InputStream inputStream = socket.getInputStream();
        byte[] bytes = new byte[MathConstant.INT_1024];
        int len;
        StringBuilder sb = new StringBuilder();
        while ((len = inputStream.read(bytes)) != MathConstant.INT_MINUS_ONE) {
            //注意指定编码格式，发送方和接收方一定要统一，建议使用UTF-8
            sb.append(new String(bytes, MathConstant.INT_ZERO, len,CommonConstant.DEFAULT_CHARSET_NAME));
        }
        System.out.println("get message from server: " + sb);

        inputStream.close();
        outputStream.close();
        socket.close();
    }
}
